package com.gpframework.module.module.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gpframework.common.config.GpframeworkConfig;
import com.gpframework.common.constant.BrandConstants;
import com.gpframework.common.constant.CacheConstants;
import com.gpframework.common.core.domain.entity.SysDept;
import com.gpframework.common.core.domain.entity.SysMenu;
import com.gpframework.common.core.domain.entity.SysUser;
import com.gpframework.common.core.redis.RedisCache;
import com.gpframework.common.enums.*;
import com.gpframework.common.exception.*;
import com.gpframework.common.utils.*;
import com.gpframework.common.weixin.common.util.AccessToken;
import com.gpframework.common.weixin.common.util.WeixinUtil;
import com.gpframework.module.brand.domain.BrandStoreUserRela;
import com.gpframework.module.brand.service.IBrandStoreUserRelaService;
import com.gpframework.module.common.domain.*;
import com.gpframework.module.common.domain.req.*;
import com.gpframework.module.common.domain.vo.*;
import com.gpframework.module.common.mapper.*;
import com.gpframework.module.common.service.*;
import com.gpframework.module.module.domain.BrandStore;
import com.gpframework.module.module.domain.BrandStoreLog;
import com.gpframework.module.module.domain.req.BrandStoreReq;
import com.gpframework.module.module.domain.req.BrandStoreUpdate;
import com.gpframework.module.module.domain.vo.BrandInfoVo;
import com.gpframework.module.module.domain.vo.BrandStoreVo;
import com.gpframework.module.module.domain.vo.BusinessDataCacheVo;
import com.gpframework.module.module.mapper.BrandInfoMapper;
import com.gpframework.module.module.mapper.BrandStoreLogMapper;
import com.gpframework.module.module.mapper.BrandStoreMapper;
import com.gpframework.module.module.service.IBrandInfoService;
import com.gpframework.module.module.service.IBrandStoreService;

import com.gpframework.module.pay.utils.joinpay.sdk.utitls.StringUtil;
import com.gpframework.module.system.domain.SysRoleMenu;
import com.gpframework.module.system.mapper.*;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName BrandStore
 * @Author gpframework
 * @Date 2022-03-25
 * @Version 1.0.0
 * @Description 门店Service业务层处理
 */
@Service
public class BrandStoreServiceImpl extends ServiceImpl<BrandStoreMapper, BrandStore> implements IBrandStoreService {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 门店日志持久层接口
     */
    @Autowired
    private BrandStoreLogMapper brandStoreLogMapper;


    /**
     * 品牌系统用户持久层接口
     */
    @Autowired
    private SysUserMapper sysUserMapper;


    /**
     * 角色菜单持久层接口
     */
    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    /**
     * 菜单持久层接口
     */
    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 标签持久层接口
     */
    @Autowired
    private CommonLabelMapper commonLabelMapper;

    /**
     * 附件持久层接口
     */
    @Autowired
    private CommonResourceMapper commonResourceMapper;

    /**
     * 品牌持久层接口
     */
    @Autowired
    private BrandInfoMapper brandInfoMapper;

    /**
     * 品牌持久层接口
     */
    @Autowired
    private IBrandInfoService brandInfoService;

    /**
     * 部门持久层接口
     */
    @Autowired
    private SysDeptMapper sysDeptMapper;


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ICommonWxAppletInfoService commonWxAppletInfoService;

    @Autowired
    private ICommonWxMenuService commonWxMenuService;

    /**
     * @Description 查询列表返回VO 用于返回给前端的列表接口
     * @Author gpframework
     * @Date 2022-03-25
     * @Param [lqw]
     * @Return List<BrandStoreVo>
     */
    @Override
    public List<BrandStoreVo> listVo(QueryWrapper<BrandStore> lqw) {
        return this.baseMapper.listVo(lqw);
    }

    /**
     * @Description 通过查询详情VO 用于返回给前端的列详情接口
     * @Author gpframework
     * @Date 2022-03-25
     * @Param [id]
     * @Return BrandStoreVo
     */
    @Override
    public BrandStoreVo getVoById(Long id) {
        BrandStoreVo vo = this.baseMapper.getVo(id);
        if (vo == null) {
            return null;
        }
        //查询门店图片
        CommonResourceReq resourceReq = new CommonResourceReq();
        resourceReq.setBrandId(vo.getBrandId());
        resourceReq.setStoreId(vo.getStoreId());
        resourceReq.setBusinessType(ResourcesBusiness.STORE_IMG.toString());
        QueryWrapper<CommonResource> lqw = new QueryWrapper<>();
        resourceReq.generatorQuery(lqw, true);
        List<CommonResourceVo> storeImgList = commonResourceMapper.listVo(lqw);
        vo.setStoreImgList(new ArrayList<>());
        storeImgList.forEach(item -> {
            vo.getStoreImgList().add(item.getResourceUrl());
        });
        //查询门店风采图片
        lqw = new QueryWrapper<>();
        resourceReq.setBrandId(vo.getBrandId());
        resourceReq.setStoreId(vo.getStoreId());
        resourceReq.setBusinessType(ResourcesBusiness.ELEGANT_DEMEANOUR.toString());
        resourceReq.generatorQuery(lqw, true);
        List<CommonResourceVo> elegantDemeanourList = commonResourceMapper.listVo(lqw);
        vo.setElegantDemeanourList(new ArrayList<>());
        elegantDemeanourList.forEach(item -> {
            vo.getElegantDemeanourList().add(item.getResourceUrl());
        });
//        //获取规格id
//        CommonOrderDetailReq commonOrderDetailReq = new CommonOrderDetailReq();
//        commonOrderDetailReq.setOrderId(vo.getOrderId());
//        CommonOrderDetailVo orderDetailVo = commonOrderDetailMapper.findByOrderId(commonOrderDetailReq);
//        if (!StringUtils.isEmpty(orderDetailVo)) {
//            vo.setProductAttrValueId(orderDetailVo.getBusinessAttrId());
//        }
        return vo;
    }

    /**
     * 添加门店
     *
     * @param brandStoreUpdate
     * @return
     */
    @Override
    @Transactional
    public BrandStoreVo add(BrandStoreUpdate brandStoreUpdate) {
        BrandStore brandStore = Convert.convert(new TypeReference<BrandStore>() {
        }, brandStoreUpdate);

//        GoodsProductAttrValueVo goodsProductAttrValueVo = goodsProductAttrValueMapper.getVo(brandStoreUpdate.getProductAttrValueId());
//        if (StringUtil.isEmpty(goodsProductAttrValueVo)) {
//            logger.info("----------规格id" + brandStoreUpdate.getGoodsSpuId() + "----------");
//            throw new DataNotFoundException("规格不存在");
//        }
//        QueryWrapper<GoodsStore> lqw = new QueryWrapper<>();
//        lqw.eq("product_attr_value_id", goodsProductAttrValueVo.getProductAttrValueId());
//        lqw.last("limit 1");
//        GoodsStore goodsStore = iGoodsStoreService.getOne(lqw);
//        if (StringUtil.isEmpty(goodsStore)) {
//            logger.info("----------门店价格id" + brandStoreUpdate.getGoodsSpuId() + "----------");
//            throw new DataNotFoundException("门店价格不存在");
//        }
        BrandInfoVo brandInfoVo = brandInfoService.getBrandInfo(brandStoreUpdate.getBrandId());
        if (StringUtil.isEmpty(brandInfoVo)) {
            logger.info("----------品牌id" + brandStoreUpdate.getBrandId() + "----------");
            throw new BaseException("品牌信息不存在");
        }
//        brandStore.setStoreLogo(brandInfoVo.getBrandLogo());
//        brandStore.setAuditStatus(CommonStatus.AUDIT.getKey().toString());
//        brandStore.setIsTryout("0");
        BrandStoreVo brandStoreVo = Convert.convert(new TypeReference<BrandStoreVo>() {
        }, brandStore);
//        brandStoreVo.setPayPrice(goodsProductAttrValueVo.getSalesPrice());
//        brandStoreVo.setSku(goodsProductAttrValueVo.getSku());
//        brandStoreVo.setPayType(goodsStore.getPayType());
//        brandStoreVo.setEffStartTime(new Date());
//        brandStoreVo.setEffEndTime(DateUtils.getAfterDay(brandStoreVo.getEffStartTime(), goodsStore.getEffDays()));
//        if (StringUtil.isNotEmpty(brandStore.getStoreAddress())
//                && (StringUtil.isEmpty(brandStore.getStoreLongitude()) || StringUtil.isEmpty(brandStore.getStoreLatitude()))) {
//            //获取地址
//            BrandStore storeLng = this.getStoreLng(brandStore);
//            brandStore.setStoreLongitude(storeLng.getStoreLongitude());
//            brandStore.setStoreLatitude(storeLng.getStoreLatitude());
//        }
//        // 有传订单id（表示关闭支付窗口再重新调起），则重新拉起支付
//        if (brandStoreUpdate.getOrderId() != null) {
//            LeshuaScanCodePayRes res = this.regenerateScanCode(brandStoreUpdate);
//            brandStore.setOrderId(brandStoreUpdate.getOrderId());
////            baseMapper.updateById(brandStore);
//            this.updateBrandStoreById(brandStore);
//            brandStoreVo.setLeshuaScanCodePayRes(res);
//        } else {
//            if (StringUtil.isNotEmpty(brandStoreUpdate.getStoreMobile())) {
                SysUser sysUser = new SysUser();
                sysUser.setBrandId(brandStoreUpdate.getBrandId());
                sysUser.setUserName(brandStoreUpdate.getStoreMobile());
                List<SysUser> sysUserList = sysUserMapper.selectUserList(sysUser);
                if (StringUtil.isNotEmpty(sysUserList) && sysUserList.size() > 0) {
                    logger.info("----------账号信息：" + sysUserList + "----------");
                    throw new BaseException("该手机号已被注册");
                }
//            }

            //新增门店
            int i = baseMapper.insert(brandStore);
            if (i > 0) {
//                BrandInfoVo brandInfoVo = brandInfoMapper.getVo(brandStore.getBrandId());
                if (StringUtil.isEmpty(brandInfoVo)) {
                    logger.info("----------品牌不存在" + brandStore.getBrandId() + "----------");
                    throw new DataNotFoundException("品牌不存在");
                }
                if (!StringUtils.isEmpty(brandStoreUpdate.getStoreImgList()) && brandStoreUpdate.getStoreImgList().size() > 0) {
                    //门店图片
                    brandStoreUpdate.getStoreImgList().forEach(item -> {
                        CommonResource resource = new CommonResource();
                        resource.setBrandId(brandInfoVo.getBrandId());
                        resource.setBrandName(brandInfoVo.getBrandName());
                        resource.setStoreId(brandStore.getStoreId());
                        resource.setStoreName(brandStore.getStoreName());
                        resource.setBusinessId(brandStore.getStoreId());
                        resource.setBusinessType(ResourcesBusiness.STORE_IMG.toString());
                        resource.setBusinessName(ResourcesBusiness.STORE_IMG.getName());
                        resource.setResourceUrl(item);
                        commonResourceMapper.insert(resource);
                    });
                }
                if (!StringUtils.isEmpty(brandStoreUpdate.getElegantDemeanourList()) && brandStoreUpdate.getElegantDemeanourList().size() > 0) {
                    //门店风采图片
                    brandStoreUpdate.getElegantDemeanourList().forEach(item -> {
                        CommonResource resource = new CommonResource();
                        resource.setBrandId(brandInfoVo.getBrandId());
                        resource.setBrandName(brandInfoVo.getBrandName());
                        resource.setStoreId(brandStore.getStoreId());
                        resource.setStoreName(brandStore.getStoreName());
                        resource.setBusinessId(brandStore.getStoreId());
                        resource.setBusinessType(ResourcesBusiness.ELEGANT_DEMEANOUR.toString());
                        resource.setBusinessName(ResourcesBusiness.ELEGANT_DEMEANOUR.getName());
                        resource.setResourceUrl(item);
                        commonResourceMapper.insert(resource);
                    });
                }

                //门店日志
                BrandStoreLog brandStoreLog = new BrandStoreLog(brandStore);
                brandStoreLog.setBusinessType(CommonStatus.AUDIT.getKey().toString());
                brandStoreLog.setBusinessName(BrandConstants.STORE_BUSINESS_TYPE_AUDIT_STR);
                brandStoreLogMapper.insert(brandStoreLog);
//                //添加订单
//                CommonOrder commonOrder = new CommonOrder(brandStore);
//                if (StringUtils.isEmpty(brandInfoVo)) {
//                    commonOrder.setBrandName(brandInfoVo.getBrandName());
//                }
//                commonOrder.setTotalPrice(goodsProductAttrValueVo.getSalesPrice());
//                commonOrder.setPayPrice(goodsProductAttrValueVo.getSalesPrice());
//                commonOrderMapper.insert(commonOrder);
//                brandStore.setOrderId(commonOrder.getOrderId());
//                brandStoreVo.setOrderId(commonOrder.getOrderId());
//                baseMapper.updateById(brandStore);
//                this.updateBrandStoreById(brandStore);
                // 微信、支付宝支付，需要调用乐刷支付，发送短信
//                LeshuaScanCodePayReq leshuaScanCodePayReq = brandStoreUpdate.getLeshuaScanCodePayReq();
//                if (StringUtil.isNotEmpty(brandStoreUpdate.getStoreMobile()) && leshuaScanCodePayReq != null && (PayEnum.ZFB.getKey().equals(leshuaScanCodePayReq.getPay_way()) || PayEnum.WECHAT.getKey().equals(leshuaScanCodePayReq.getPay_way()))) {
//                    // 调用乐刷扫码支付
//                    LeshuaScanCodePayRes res = iCommonOrderService.scanCode(commonOrder, leshuaScanCodePayReq, null);
//                    brandStoreVo.setLeshuaScanCodePayRes(res);
//                    // 发送新增门店支付短信
//                    BrandSendSmsReq brandSendSmsReq = new BrandSendSmsReq();
//                    brandSendSmsReq.setBrandId(0L);
//                    brandSendSmsReq.setStoreId(0L);
//                    brandSendSmsReq.setPhonenumber(brandStoreUpdate.getStoreMobile());
//                    brandSendSmsReq.setBusinessType(PhoneMsgTypeEnum.PAY_STORE_REGISTER.getKey());
//                    brandSendSmsReq.setBusinessName(PhoneMsgTypeEnum.PAY_STORE_REGISTER.getName());
//                    brandSendSmsReq.setAreaCode(Constants.MOBILE_AREA_CODE_CHINA);
//                    brandSendSmsReq.setSendContent(res.getResource_url() + " 请保存二维码到微信扫码支付");
//                    brandSendSmsReq.setContent(res.getResource_url() + " 请保存二维码到微信扫码支付");
//                    brandSendSmsReq.setCreateClassName(getClass().getName());
//                    brandSendSmsReq.setReceiveUserId(brandStore.getStoreId());
//                    brandSendSmsReq.setReceiveUserName(brandStore.getStoreName());
//                    iCommonPhoneMsgTemplateService.sendSms(brandSendSmsReq);
//                }
//                //添加订单详情
//                CommonOrderDetail commonOrderDetail = new CommonOrderDetail(commonOrder);
//                commonOrderDetail.setBusinessId(brandStoreUpdate.getGoodsSpuId());
//                commonOrderDetail.setBusinessAttrId(brandStoreUpdate.getProductAttrValueId());
//                commonOrderDetail.setGoodsSinglePrice(goodsProductAttrValueVo.getSalesPrice());
//                commonOrderDetail.setGoodsConcessionary(BigDecimal.ZERO);
//                commonOrderDetail.setGoodsTotalPrice(goodsProductAttrValueVo.getSalesPrice());
//                commonOrderDetailMapper.insert(commonOrderDetail);
//                //门店订单缓存
//                String key = CacheConstants.BRAND_ORDER + commonOrder.getOrderId();
//                redisCache.setCacheObject(key, CacheConstants.CACHE_KEY_WORD);
//                redisCache.expire(key, CacheConstants.CACHE_OVERDUE_TEN);
                // 门店添加默认问卷
                // 获取品牌默认问卷
//                QueryWrapper<CommonProblem> cpLqw = new QueryWrapper<>();
//                cpLqw.eq("brand_id", brandStore.getBrandId());
//                cpLqw.eq("sort", 0); // 用sort=0作标识，代表默认的数据
//                cpLqw.eq("del_status", Constants.DEL_STATUS_FALSE);
//                List<CommonProblem> commonProblemList = commonProblemService.list(cpLqw);
//                if (CollectionUtils.isNotEmpty(commonProblemList)) {
//                    Long problemId = commonProblemList.get(0).getProblemId();
//                    CommonProblemUpdate commonProblemUpdate = new CommonProblemUpdate();
//                    commonProblemUpdate.setBrandId(brandStore.getBrandId());
//                    commonProblemUpdate.setProblemId(problemId);
//                    List<Long> storeIds = new ArrayList<>();
//                    storeIds.add(brandStore.getStoreId());
//                    commonProblemUpdate.setStoreIds(storeIds);
//                    commonProblemService.saveProblemRela(commonProblemUpdate);
//                }
//            }
        }
        return brandStoreVo;
    }

    /**
     * 设置角色菜单
     *
     * @param sysUser
     * @param brandRoleId
     */
    public void initializeRoleMenu(SysUser sysUser, Long brandRoleId) {
        SysMenu sysMenu = new SysMenu();
        sysMenu.setBrandId(sysUser.getBrandId());
        sysMenu.setMenuName("日志管理");
        List<SysMenu> sysMenuList = sysMenuMapper.selectMenuList(sysMenu);
        //角色菜单list
        ArrayList<SysRoleMenu> sysRoleMenuList = new ArrayList<>();

        for (SysMenu menu : sysMenuList) {
            sysMenu = new SysMenu();
            sysMenu.setBrandId(sysUser.getBrandId());
            sysMenu.setParentId(menu.getMenuId());
            List<SysMenu> sysMenuList2 = sysMenuMapper.selectMenuList(sysMenu);
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setBrandId(sysUser.getBrandId());
            sysRoleMenu.setBrandMenuId(menu.getMenuId());
            sysRoleMenu.setBrandRoleId(brandRoleId);
            sysRoleMenuList.add(sysRoleMenu);
            for (SysMenu sysMenu1 : sysMenuList2) {
                sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setBrandId(sysUser.getBrandId());
                sysRoleMenu.setBrandMenuId(sysMenu1.getMenuId());
                sysRoleMenu.setBrandRoleId(brandRoleId);
                sysRoleMenuList.add(sysRoleMenu);
            }
        }
        sysRoleMenuMapper.batchRoleMenu(sysRoleMenuList);
    }

    /**
     * 小程序门店列表
     *
     * @param brandStoreReq
     * @return
     */
    @Override
    public List<BrandStoreVo> homeListVo(BrandStoreReq brandStoreReq) {
        String key = CacheConstants.CACHE_BRAND_STORE_LIST + brandStoreReq.getBrandId();
        if (StringUtil.isNotEmpty(brandStoreReq.getShowStatus())) {
            key += CacheConstants.PACKET_IDENTIFICATION + brandStoreReq.getShowStatus();
        }
        if (StringUtil.isNotEmpty(brandStoreReq.getAreaIds())) {
            key += CacheConstants.PACKET_IDENTIFICATION + brandStoreReq.getAreaIds();
        }
        //获取缓存
        List<BrandStoreVo> brandStoreVoList = redisCache.getCacheObject(key);
        if (StringUtil.isNotEmpty(brandStoreVoList) && brandStoreVoList.size() > 0) {
            return brandStoreVoList;
        }
        //从数据库获取数据
        QueryWrapper<BrandStore> lqw = new QueryWrapper<>();
        brandStoreReq.generatorQuery(lqw, true);
        brandStoreVoList = this.baseMapper.listVo(lqw);
        //资源查询
        CommonResourceReq resourceReq;
        //标签查询
        CommonLabelReq labelReq;
        //门店权限标识
        List<String> componentList;
        //门店权限标识查询
        CommonWxMenuReq commonWxMenuReq = new CommonWxMenuReq();
        //品牌信息
        BrandInfoVo brandInfoVo = brandInfoMapper.getVo(brandStoreReq.getBrandId());
        for (BrandStoreVo brandStoreVo : brandStoreVoList) {
            //品牌logo
            if (StringUtil.isNotEmpty(brandInfoVo.getBrandLogo())) {
                brandStoreVo.setBrandLogo(brandInfoVo.getBrandLogo());
            }
            //获取门店权限
            commonWxMenuReq.setBrandId(brandStoreVo.getBrandId());
            commonWxMenuReq.setStoreId(brandStoreVo.getStoreId());
            componentList = commonWxMenuService.getStoreComponentList(commonWxMenuReq);
            brandStoreVo.setComponentList(componentList);
            //获取附件
            resourceReq = new CommonResourceReq(brandStoreVo);
            QueryWrapper<CommonResource> resourceVoLwq = new QueryWrapper<>();
            resourceReq.setBusinessType(ResourcesBusiness.STORE_IMG.toString());
            resourceReq.generatorQuery(resourceVoLwq, true);
            List<CommonResourceVo> commonResourceVoList = commonResourceMapper.listVo(resourceVoLwq);
            brandStoreVo.setCommonResourceVoList(commonResourceVoList);
            //获取标签
            labelReq = Convert.convert(new TypeReference<CommonLabelReq>() {
            }, brandStoreVo);
            labelReq.setStoreId(brandStoreVo.getStoreId());
            List<CommonLabelVo> storeLabelList = commonLabelMapper.getStoreLabel(labelReq);
            brandStoreVo.setStoreLabelList(storeLabelList);

            // 获取风采照
            resourceReq = new CommonResourceReq();
            resourceReq.setBusinessId(brandStoreVo.getStoreId());
            resourceVoLwq = new QueryWrapper<>();
            resourceReq.setBusinessType(ResourcesBusiness.ELEGANT_DEMEANOUR.toString());
            resourceReq.generatorQuery(resourceVoLwq, true);
            List<CommonResourceVo> elegantDemeanourList = commonResourceMapper.listVo(resourceVoLwq);
            if (CollectionUtils.isNotEmpty(elegantDemeanourList)) {
                List<String> resourceUrlList = elegantDemeanourList.stream()
                        .filter(e -> e != null && com.gpframework.common.utils.StringUtils.isNotBlank(e.getResourceUrl()))
                        .map(e -> e.getResourceUrl())
                        .collect(Collectors.toList());
                brandStoreVo.setElegantDemeanourList(resourceUrlList);
            }
        }
        if (StringUtil.isNotEmpty(brandStoreVoList) && brandStoreVoList.size() > 0) {
            //设置缓存
            redisCache.setCacheObject(key, brandStoreVoList, CacheConstants.CACHE_OVERDUE_TEN);
        }
        return brandStoreVoList;
    }

    /**
     * 修改门店信息
     *
     * @param brandStoreUpdate
     * @return
     */
    @Override
    @Transactional
    public boolean edit(BrandStoreUpdate brandStoreUpdate) {
        //修改门店信息
        BrandStore brandStore = Convert.convert(new TypeReference<BrandStore>() {
        }, brandStoreUpdate);
//        this.baseMapper.updateById(brandStore);
        this.updateBrandStoreById(brandStore);
        //删除门店图片
        CommonResource delResource = new CommonResource();
        delResource.setBrandId(brandStore.getBrandId());
        delResource.setStoreId(brandStore.getStoreId());
        delResource.setBusinessType(ResourcesBusiness.STORE_IMG.toString());
        commonResourceMapper.deleteByBrandIdAndStore(delResource);
        //删除门店风采图
        delResource.setBusinessType(ResourcesBusiness.ELEGANT_DEMEANOUR.toString());
        commonResourceMapper.deleteByBrandIdAndStore(delResource);
        //新增门店图片
        if (!StringUtils.isEmpty(brandStoreUpdate.getStoreImgList()) && brandStoreUpdate.getStoreImgList().size() > 0) {
            //门店图片
            brandStoreUpdate.getStoreImgList().forEach(item -> {
                CommonResource resource = new CommonResource();
                resource.setBrandId(brandStore.getBrandId());
                resource.setBrandName(brandStore.getBrandName());
                resource.setStoreId(brandStore.getStoreId());
                resource.setStoreName(brandStore.getStoreName());
                resource.setBusinessId(brandStore.getStoreId());
                resource.setBusinessType(ResourcesBusiness.STORE_IMG.toString());
                resource.setBusinessName(ResourcesBusiness.STORE_IMG.getName());
                resource.setResourceUrl(item);
                commonResourceMapper.insert(resource);
            });
        }
        //新增门店风采图片
        if (!StringUtils.isEmpty(brandStoreUpdate.getElegantDemeanourList()) && brandStoreUpdate.getElegantDemeanourList().size() > 0) {
            //门店风采图片
            brandStoreUpdate.getElegantDemeanourList().forEach(item -> {
                CommonResource resource = new CommonResource();
                resource.setBrandId(brandStore.getBrandId());
                resource.setBrandName(brandStore.getBrandName());
                resource.setStoreId(brandStore.getStoreId());
                resource.setStoreName(brandStore.getStoreName());
                resource.setBusinessId(brandStore.getStoreId());
                resource.setBusinessType(ResourcesBusiness.ELEGANT_DEMEANOUR.toString());
                resource.setBusinessName(ResourcesBusiness.ELEGANT_DEMEANOUR.getName());
                resource.setResourceUrl(item);
                commonResourceMapper.insert(resource);
            });
        }
        String storeName = brandStoreUpdate.getStoreName();
        Long storeId = brandStoreUpdate.getStoreId();
        if (!StringUtils.isEmpty(brandStoreUpdate.getBrandUserId())) {
            SysUser sysUser = sysUserMapper.findByUserName(brandStoreUpdate.getStoreMobile(), brandStoreUpdate.getBrandId());
            if (!StringUtils.isEmpty(sysUser) && !sysUser.getBrandUserId().equals(brandStoreUpdate.getBrandUserId())) {
                throw new BaseException("当前手机号已被使用");
            }
            SysUser user = sysUserMapper.selectUserById(brandStoreUpdate.getBrandUserId());
            user.setNickName(storeName);
            user.setUserName(brandStoreUpdate.getStoreMobile());
            user.setPhonenumber(brandStoreUpdate.getStoreMobile());
            sysUserMapper.updateUser(user);
        }
        SysUser sysUser = new SysUser();
        sysUser.setStoreId(brandStoreUpdate.getStoreId());
        sysUser.setStatus(YesNoEnum.YES.getKey());
        //修改门店状态
        if (CommonStatus.IS_USING_STATUS.getKey().equals(brandStoreUpdate.getStoreStatus())) {
            sysUser.setStatus(YesNoEnum.NO.getKey());
        }
        if (StringUtil.isNotEmpty(sysUser.getStoreId())) {
            sysUserMapper.updateUserStatus(sysUser);
        }

//        // 更新‘会员出入场’门店名称
//        UpdateWrapper<UserEntrance> ueUpdate = new UpdateWrapper<>();
//        ueUpdate.set("store_name", storeName);
//        ueUpdate.eq("store_id", storeId);
//        userEntranceService.update(ueUpdate);
//        // 更新’分配记录‘门店名称
//        UpdateWrapper<UserFollow> ufUpdate = new UpdateWrapper<>();
//        ufUpdate.set("store_name", storeName);
//        ufUpdate.eq("store_id", storeId);
//        userFollowService.update(ufUpdate);
//        // 更新‘跟进日志’门店名称
//        UpdateWrapper<UserFollowLog> uflUpdate = new UpdateWrapper<>();
//        uflUpdate.set("store_name", storeName);
//        uflUpdate.eq("store_id", storeId);
//        userFollowLogService.update(uflUpdate);
//        // 更新’会员预约课程‘门店名称
//        UpdateWrapper<UserSubscribeCourse> usclUpdate = new UpdateWrapper<>();
//        usclUpdate.set("store_name", storeName);
//        usclUpdate.eq("store_id", storeId);
//        userSubscribeCourseService.update(usclUpdate);
//        // 更新‘用户余额/押金变更日志’门店名称
//        UpdateWrapper<UserBalanceModifyLog> ubmlUpdate = new UpdateWrapper<>();
//        ubmlUpdate.set("store_name", storeName);
//        ubmlUpdate.eq("store_id", storeId);
//        userBalanceModifyLogService.update(ubmlUpdate);
        // 更新‘品牌部门管理’门店名称
        SysDept dept = new SysDept();
        dept.setDeptName(storeName);
        dept.setStoreId(storeId);
        sysDeptMapper.updateStoreName(dept);
        //删除缓存
        String key = CacheConstants.CACHE_STORE_INFO + storeId;
        redisCache.deleteObject(key);
        key = CacheConstants.CACHE_BRAND_STORE_LIST + brandStoreUpdate.getBrandId();
        redisCache.deleteObject(key);
        return true;
    }

    @Override
    public BrandStoreVo getStoreVoById(Long storeId) {
        if (storeId == null) {
            return null;
        }

        return this.baseMapper.getStoreVoById(storeId);
    }

    /**
     * 查询品牌门店列表
     *
     * @param brandStoreReq
     */
    @Override
    public List<BrandStoreVo> findByBrandId(BrandStoreReq brandStoreReq) {
        return this.baseMapper.findByBrandId(brandStoreReq);
    }

    @Override
    public List<BrandStoreVo> findByStoreId(Long storeId) {
        return this.baseMapper.findByStoreId(storeId);
    }

    /**
     * 查询门店信息
     *
     * @param brandStoreReq
     * @return
     */
    @Override
    public BrandStoreVo get(BrandStoreReq brandStoreReq) {
        return this.baseMapper.get(brandStoreReq);
    }

    /**
     * 用户门店列表
     *
     * @param lqw
     * @return
     */
    @Override
    public List<BrandStoreVo> userStoreList(QueryWrapper<BrandStoreUserRela> lqw) {
        return this.baseMapper.userStoreList(lqw);
    }

    @Override
    public List<BrandStoreVo> getStoreList() {
        return this.baseMapper.getStoreList();
    }

    /**
     * 获取门店信息
     *
     * @param storeId
     * @return
     */
    @Override
    public BrandStoreVo getBrandStore(Long storeId) {
        //缓存key
        String key = CacheConstants.CACHE_STORE_INFO + storeId;
        //门店信息
        BrandStoreVo brandStoreVo = redisCache.getCacheObject(key);
        //信息不存在
        if (StringUtil.isEmpty(brandStoreVo)) {
            //删除缓存
            redisCache.deleteObject(key);
            //数据库获取门店信息
            brandStoreVo = this.baseMapper.getVo(storeId);
            //风采照
            CommonResourceReq resourceReq = new CommonResourceReq();
            resourceReq.setBrandId(brandStoreVo.getBrandId());
            resourceReq.setStoreId(brandStoreVo.getStoreId());
            resourceReq.setBusinessId(brandStoreVo.getStoreId());
            resourceReq.setBusinessType(ResourcesBusiness.ELEGANT_DEMEANOUR.toString());
            QueryWrapper<CommonResource> lqw = new QueryWrapper<>();
            resourceReq.generatorQuery(lqw, true);
            List<CommonResourceVo> resourceVos = commonResourceMapper.listVo(lqw);
            List<String> resourceUrlList;
            //风采照
            if (StringUtil.isNotEmpty(resourceVos) && resourceVos.size() > 0) {
                resourceUrlList = resourceVos.stream().map(CommonResourceVo::getResourceUrl).collect(Collectors.toList());
                brandStoreVo.setElegantDemeanourList(resourceUrlList);
            }
            //门店照片
            lqw = new QueryWrapper<>();
            resourceReq.setBusinessType(ResourcesBusiness.STORE_IMG.toString());
            resourceReq.generatorQuery(lqw, true);
            if (StringUtil.isNotEmpty(resourceVos) && resourceVos.size() > 0) {
                resourceUrlList = resourceVos.stream().map(CommonResourceVo::getResourceUrl).collect(Collectors.toList());
                brandStoreVo.setStoreImgList(resourceUrlList);
            }
            //设置缓存信息
            redisCache.setCacheObject(key, brandStoreVo);
            //设置过期时间
            redisCache.expire(key, CacheConstants.CACHE_OVERDUE_AN_HOUR);
        }
        return brandStoreVo;
    }

    @Override
    public int updateBrandStoreById(BrandStore brandStore) {
        //缓存key
        String key = CacheConstants.CACHE_STORE_INFO + brandStore.getStoreId();
        //删除缓存
        redisCache.deleteObject(key);
        return this.baseMapper.updateById(brandStore);
    }

    @Override
    public boolean removeByStoreIds(List<Long> storeIds) {
        boolean remove = removeByIds(storeIds);
        if (remove) {
            // 删除门店对应部门
            sysDeptMapper.deleteDeptByStoreIds(storeIds);
        }
        return remove;
    }

    /**
     * 获取品牌门店列表
     *
     * @param brandId
     * @return
     */
    @Override
    public List<BrandStoreVo> getBrandStoreList(Long brandId) {
        BrandStoreReq brandStoreReq = new BrandStoreReq();
        brandStoreReq.setBrandId(brandId);
        QueryWrapper<BrandStore> lqw = new QueryWrapper<>();
        brandStoreReq.generatorQuery(lqw, true);
        return this.baseMapper.listVo(lqw);
    }



    /**
     * 生成门店二维码
     *
     * @param brandStoreReq
     * @return
     */
    @Override
    public boolean genStoreQrCode(BrandStoreReq brandStoreReq) {
        BrandStore brandStore = this.baseMapper.selectById(brandStoreReq.getStoreId());
        if (StringUtil.isEmpty(brandStore)) {
            throw new DataExistException();
        }
        //获取appId
        CommonWxAppletInfoReq wxAppletInfoReq = new CommonWxAppletInfoReq();
        wxAppletInfoReq.setWxType(BrandConstants.WE_CHAT_MEMBER);
        wxAppletInfoReq.setBrandId(brandStore.getBrandId());
        CommonWxAppletInfoVo wxAppletInfoVo = commonWxAppletInfoService.findByBrandIdAndWxType(wxAppletInfoReq);
        //获取默认的小程序信息
        if (StringUtil.isEmpty(wxAppletInfoVo)) {
            wxAppletInfoReq.setBrandId(BrandConstants.DEFAULT_BRAND_ID);
            wxAppletInfoVo = commonWxAppletInfoService.findByBrandIdAndWxType(wxAppletInfoReq);
        }
        //默认路径
        String page = SmallProgramPageEnum.SMALL_PROGRAM_HOME.getUrl();
        //前端传参
        if (StringUtil.isNotEmpty(brandStoreReq.getPage())) {
            page = brandStoreReq.getPage();
        }
        String qrCodePath = genStoreQrCode(brandStore, wxAppletInfoVo, page);
        brandStore.setStoreQrcodeApp(qrCodePath);
        this.updateById(brandStore);
        return true;
    }

    /**
     * 生成门店二维码
     *
     * @param brandStore     门店信息
     * @param wxAppletInfoVo 小程序信息
     * @param page           跳转路径
     * @return
     */
    private String genStoreQrCode(BrandStore brandStore, CommonWxAppletInfoVo wxAppletInfoVo, String page) {
        AccessToken accessToken = WeixinUtil.getBrandAccessToken(wxAppletInfoVo.getBrandId(), BrandConstants.WE_CHAT_EMPLOYEE, wxAppletInfoVo.getAppId(), wxAppletInfoVo.getAppSecret());
        //生成二维码
        int x = (int) (Math.random() * 100);
        String newFileName = DateUtils.getDate("yyyyMMddHHmmssSSS") + x + ".png";
        return WxQrCode.getminiqrQr(brandStore.getBrandId(), accessToken.getAccess_token(), GpframeworkConfig.getProfile(), newFileName, String.valueOf(brandStore.getStoreId()), page, null);
    }

    /**
     * 设置业务数据
     *
     * @param businessDataCacheVo
     * @return
     */
    @Override
    public boolean saveBusinessData(BusinessDataCacheVo businessDataCacheVo) {
        String key = CacheConstants.BUSINESS_DATA_CACHE + businessDataCacheVo.getBrandId() + CacheConstants.PACKET_IDENTIFICATION + businessDataCacheVo.getStoreId() + CacheConstants.PACKET_IDENTIFICATION + businessDataCacheVo.getBusinessType() + CacheConstants.PACKET_IDENTIFICATION + businessDataCacheVo.getPhone();
        businessDataCacheVo.setCacheKey(key);
        redisCache.setCacheObject(key, businessDataCacheVo);
        //当天零时
        Date dayDate = DateUtils.getTodayStartDate();
        //第二天零时
        Date afterDay = DateUtils.getAfterDay(dayDate, 1);
        //两个时间的时间差
        long earlyMorningTime = DateUtils.getDateMinDiff(afterDay, new Date());
        redisCache.expire(key, earlyMorningTime);
        return true;
    }

    /**
     * 获取业务数据列表
     *
     * @param businessDataCacheVo
     * @return
     */
    @Override
    public List<BusinessDataCacheVo> getBusinessData(BusinessDataCacheVo businessDataCacheVo) {
        String key = CacheConstants.BUSINESS_DATA_CACHE + businessDataCacheVo.getBrandId() + CacheConstants.PACKET_IDENTIFICATION + businessDataCacheVo.getStoreId();
        return redisCache.getGroupObject(key);
    }

    /**
     * 删除业务数据缓存
     *
     * @param cacheKey
     * @return
     */
    @Override
    public boolean delBusinessData(String cacheKey) {
        return redisCache.deleteObject(cacheKey);
    }

    /**
     * 修改门店状态与区域地址
     *
     * @param brandStoreUpdate
     * @return
     */
    @Override
    public boolean updateStoreInfo(BrandStoreUpdate brandStoreUpdate) {
        //缓存key
        String brandKey = CacheConstants.CACHE_BRAND_STORE_LIST + brandStoreUpdate.getBrandId();
        String storeKey = CacheConstants.CACHE_STORE_INFO + brandStoreUpdate.getStoreId();
        //删除缓存
        redisCache.deleteObject(brandKey);
        redisCache.deleteObject(storeKey);
        BrandStore brandStore = new BrandStore(brandStoreUpdate);
        baseMapper.updateById(brandStore);
        //删除缓存
        redisCache.deleteObject(brandKey);
        redisCache.deleteObject(storeKey);
        return true;
    }
}
